'use strict';

const {
	Controller
} = require('egg');
const svg = require("svg-captcha")
const path = require("path")
const fs = require("fs")
class UserController extends Controller {
	async loginout(){
		this.ctx.session.id=""
		this.ctx.body={code:"2001",info:"退出登录成功"}
	}
	async userinfo(){
		let id=this.ctx.session.id
		if(!id){
			this.ctx.body={code:4004,info:"登录失效,重新登录"}
		}else{
			let sql=`select userimg,nickname,tel from user where id=${id}`
			let arr=await this.ctx.app.mysql.query(sql)
			this.ctx.body={code:2009,info:arr[0]}
		}
	}
	async login() {
		let {tel,pwd}=this.ctx.request.body
	    let sql1=`select * from user where tel="${tel}"`
		console.log(sql1)
		let arr=await this.ctx.app.mysql.query(sql1)
		if(!arr[0]){
			this.ctx.body={code:49,info:"手机号未注册"}
			return 
		}
		let sql2=`select * from user where tel="${tel}" and pwd="${pwd}"`
		
		let arr2=await this.ctx.app.mysql.query(sql2)
		if(!arr2[0]){
			this.ctx.body={code:4002,info:"密码错误"}
			return 
		}
		this.ctx.session.id=arr2[0].id//缓存当前登录用户的id
		this.ctx.body={code:2004,info:"登录成功"}
		
	}
	async register() {
		//fdata.append("userimg",userimg)
		// 	fdata.append("nickname",nickname)
		// 	fdata.append("tel",tel)
		// 	fdata.append("pwd",pwd)
		// 	fdata.append("verif",verif)
		// 	fdata.append("sign",sign)
		console.log(this.ctx.request.body)
		let files = this.ctx.request.files
		let {
			userimg,
			nickname,
			tel,
			pwd,
			verif,
			sign
		} = this.ctx.request.body
		// console.log(this.ctx.session.svgtext,verif)
		if (this.ctx.session.svgtext.toUpperCase() != verif.toUpperCase()) {
			this.ctx.body = {
				code: 42,
				info: "验证码错误"
			}
			return
		}

		let sql1 = `select * from user where tel="${tel}"`
		let arr = await this.app.mysql.query(sql1)
		if (arr[0]) {
			this.ctx.body = {
				code: 43,
				info: "手机号已经注册"
			}
			return
		}


		//1.
		if (!files[0]) {
			userimg = "/server/userimg/2.png"
		} else {
			let oldpath = files[0].filepath
			let imgname = path.basename(oldpath)
			let newpath = __dirname + "/../public/server/userimg/" + imgname
			fs.copyFileSync(oldpath, newpath)
			userimg = "/server/userimg/" + imgname
		}
		let sql2 = `insert into user (userimg,nickname,tel,pwd,sign) values 
		("${userimg}","${nickname}","${tel}","${pwd}","${sign}")`
		let obj = await this.ctx.app.mysql.query(sql2)
		// if(obj.)
		this.ctx.body = {
			code: 25,
			info: "注册成功"
		}

	};
	async verif() {
		const {
			ctx
		} = this;
		var svgobj = svg.create({
			size: 4, // size of random string
			ignoreChars: '0o1i', // filter out some characters like 0o1i
			noise: 1, // number of noise lines
			color: true, // characters will have distinct colors instead of grey, true if background option is set
			background: '#cc9966' // background color of the svg image
		})
		this.ctx.session.svgtext = svgobj.text //图形中的文字
		ctx.body = svgobj.data; //图形
	}



}

module.exports = UserController;